﻿namespace com.game.manager
{
    using com.game.Interface.Tick;
    using System;
    using System.Collections.Generic;
    using UnityEngine;

    public class TickManager : ITickManager
    {
        private float clientTotalTime;
        private int frameRate = Application.targetFrameRate;
        private float frameSlice;
        public static TickManager instance;
        private float lastSec;
        private float lastSyncTime;
        private float offsetTime;
        private List<ITick> tickList;

        static TickManager()
        {
            if (instance == null)
            {
            }
            instance = new TickManager();
        }

        public TickManager()
        {
            this.frameSlice = 1f / ((float) this.frameRate);
            this.clientTotalTime = Time.time;
            this.lastSyncTime = Time.time;
            this.lastSec = 0f;
            this.tickList = new List<ITick>();
        }

        public void addTick(ITick tick)
        {
            if (this.tickList.IndexOf(tick) == -1)
            {
                this.tickList.Add(tick);
            }
        }

        public float getClientTotalTime()
        {
            return this.clientTotalTime;
        }

        public float getSyncOffsetTime()
        {
            return this.offsetTime;
        }

        public bool inTick(ITick tick)
        {
            return (this.tickList.IndexOf(tick) > -1);
        }

        private void OnTick(int times, float dt)
        {
            for (int i = 0; i < this.tickList.Count; i++)
            {
                if (this.tickList[i] != null)
                {
                    this.tickList[i].Update(times, dt);
                }
            }
        }

        public void removeTick(ITick tick)
        {
            if (this.tickList.IndexOf(tick) > -1)
            {
                this.tickList.Remove(tick);
            }
        }

        public void Update()
        {
            this.clientTotalTime = Time.time;
            this.offsetTime = this.clientTotalTime - this.lastSyncTime;
            float dt = this.offsetTime - this.lastSec;
            int num2 = ((int) dt) / this.frameRate;
            if (num2 < 1)
            {
                num2 = 1;
            }
            this.OnTick((dt <= this.frameSlice) ? 1 : num2, dt);
            this.lastSec = this.offsetTime;
        }
    }
}

